<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Exports\MemberExport;
use App\Http\Forms\BannerForm;
use App\Http\Forms\MemberForm;
use App\Http\Forms\ShopForm;
use App\Http\Forms\ShopRecommendForm;
use App\Modules\Good\Models\Good;
use App\Modules\Package\Models\GoodPackage;
use App\Modules\Shop\Manager;
use App\Modules\Shop\Models\Banner;
use App\Modules\Shop\Models\Category;
use App\Modules\Shop\Shop;
use App\Modules\Shop\Models\Group;
use App\Modules\Shop\ShopRecommend;
use App\Modules\User\Models\Member;
use App\Modules\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use function Psy\sh;

class ShopController extends Controller
{
    /**
     * 门店列表
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function index()
    {
        $this->authorize('shop');
        $data = Shop::query()
            ->orderBy('sort', 'desc')
            ->paginate(20);
        $category = DB::select("SELECT id,name FROM categories ORDER BY SORT DESC");
        $category = array_column($category, "name", "id");

        $group = Group::query()->pluck('name', 'id')->all();

        if ($data->items()) {
            foreach ($data as $k => $v) {
                if ($v->category_ids) {
                    $tmp = [];
                    foreach ($v->category_ids as $id) {
                        $tmp[] = $category[$id];
                    }
                    $v->category = $tmp;
                }
                if ($v->type_id) {
                    $v->type = $category[$v->type_id];
                }
            }
        }

        $sidebar = 'shop';
        return view('shop.index', compact('data', 'sidebar', 'group'));
    }

    /**
     * 创建门店-》页面
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function create()
    {
        $this->authorize('shop_store_add');
        $form = $this->form(ShopForm::class, [
            'method' => 'PUT',
            'url' => route('admin.shop.store'),
        ]);
        $sidebar = 'shop';
        $flag = 'shops';//用于区分表单页面的js
        return view('shop.form', compact('form', 'sidebar', 'flag'));
    }

    /**
     * 创建门店逻辑
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function store()
    {
        $this->authorize('shop_store_add');
        $form = $this->form(ShopForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();

        $data['status'] = Shop::STATUS_CLOSE;
        $data['starting_price'] *= 100;

        // $data['cover'] = "";//临时设置为空
        //设置商品种类的名称以及类别的名称
        if (empty($data['type_id'])) {
            return redirect()->back()->withErrors('请选择门店类别');
        }

        if (empty($data['category_ids'])) {
            return redirect()->back()->withErrors('请选择商品种类');
        }
        $ids = implode(",", $data['category_ids']);
        $category = DB::select("SELECT * FROM categories WHERE ID IN ({$ids}) AND DELETED_AT IS NULL ORDER BY SORT DESC");
        $category = array_column($category, "name");
        $data['category'] = $category;

        $type = DB::select("SELECT * FROM categories WHERE ID = {$data['type_id']} AND DELETED_AT IS NULL ORDER BY SORT DESC");

        $data['type'] = $type[0]->name ?? '';
        $data['is_photography'] = $data['type'] == '婚纱摄影' ? 1 : 0;//判断门店是否是婚纱摄影门店

        Shop::query()->create($data);
        Redis::del("shop:info");
        return redirect()->route('admin.shop.index');
    }

    /**
     * 编辑门店->页面
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function edit($id)
    {
        $this->authorize('shop_store_edit');
        $shop = Shop::query()->find($id);
        $shop->starting_price /= 100;

        if (!empty($shop->category_ids)) {
            $category = Category::query()->whereIn("id", $shop->category_ids)->pluck("name", "id")->all();
        } else {
            $category = [];
            $shop->category_ids = [];
            if ($shop->category) {
                $category = Category::query()->whereIn("name", $shop->category)->pluck("name", "id")->all();
                $shop->category_ids = array_keys($category);
            }

        }

        // $groupData = [0 => '无'];
        $groupData = Group::query()->pluck('name', 'id')->all();
        array_unshift($groupData, '无');

        if (!$shop->type_id) {
            $type_id = Category::query()->where("name", $shop->type)->first();
            if (!$type_id) goto BEGIN;
            $shop->type_id = $type_id->id;
        }
        BEGIN:
        $form = $this->form(ShopForm::class, [
            'method' => 'POST',
            'url' => route('admin.shop.update', ['id' => $id]),
            'model' => $shop,
        ], [
            'category' => $category,
            'groups' => $groupData
        ]);

        $longitude = $shop->longitude;//经度
        $latitude = $shop->latitude;//纬度

        $longitude = $longitude == "" ? 103.832475 : $longitude;
        $latitude  = $latitude  == "" ? 36.065466  : $latitude;
        $sidebar = 'shop';
        $flag = 'shops';//用于区分表单页面的js
        return view('shop.form', compact('form', 'sidebar', 'flag', 'longitude', 'latitude'));
    }

    /**
     * 编辑门店逻辑
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function update($id)
    {
        $this->authorize('shop_store_edit');
        $form = $this->form(ShopForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }

        $data = $form->getFieldValues();
//        $data['cover'] = "";//临时设置为空

        //设置商品种类的名称以及类别的名称
        $ids = implode(",", $data['category_ids']);
        $category = DB::select("SELECT * FROM categories WHERE ID IN ({$ids}) AND DELETED_AT IS NULL ORDER BY SORT DESC");
        $category = array_column($category, "name");
        $data['category'] = $category;
        $type = DB::select("SELECT * FROM categories WHERE ID = {$data['type_id']} AND DELETED_AT IS NULL ORDER BY SORT DESC");
        $data['type'] = $type[0]->name;
        $data['starting_price'] *= 100;


        Shop::query()->where('id', $id)
            ->update($data);
        Redis::del("shop:info");
        return redirect()->route('admin.shop.index');
    }

    /**
     * 排序
     * @param Request $request
     * @return null
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function changeSort(Request $request)
    {
        $this->authorize('shop');
        $id = $request->input('id');
        $sort = $request->input('sort');
        Shop::query()
            ->where('id', $id)
            ->update(['sort' => $sort]);
        return null;
    }

    /**
     * 店铺开关门
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function status($id)
    {
        $this->authorize('shop_store_on_off');
        $shop = Shop::query()->where('id', $id)
            ->first();
        if ($shop->status == Shop::STATUS_OPEN) {
            $shop->update([
                'status' => Shop::STATUS_CLOSE,
            ]);
        } else {
            $shop->update([
                'status' => Shop::STATUS_OPEN,
            ]);
        }
        Redis::del("shop:info");
        return redirect()->route('admin.shop.index');
    }

//    public function categoryList()
//    {
//        $data = Category::query()->get();
//        $sidebar = 'category';
//        return view('shop.category', compact('data', 'sidebar'));
//    }
//
//    public function storeCategory(Request $request)
//    {
//        $data = $request->all();
//        Category::query()
//            ->create($data);
//        return redirect()->route('admin.shop.category');
//    }
//
//    public function deleteCategory($id)
//    {
//        Category::query()
//            ->where('id', $id)
//            ->delete();
//        return redirect()->route('admin.shop.category');
//    }

    /**
     * 展示图列表
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function bannerList()
    {
        $this->authorize('shop_store_cover');
        $data = Banner::query()
            ->where('type', Banner::TYPE_SHOP)
            ->get();
        foreach ($data as $value) {
            $shop = Shop::query()->find($value->shop_id);
            $value->shop = $shop->name;
        }
        $sidebar = 'banner';
        return view('shop.banner', compact('data', 'sidebar'));
    }

    /**
     * 添加展示图-》页面
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function createBanner()
    {
        $this->authorize('shop_store_cover_add');
        $shop = Shop::query()
            ->get()
            ->pluck('name', 'id')
            ->all();
        $form = $this->form(BannerForm::class, [
            'method' => 'PUT',
            'url' => route('admin.shop.banner.store'),
        ], [
            'shop' => $shop,
        ]);
        $sidebar = 'banner';
        $flag = 'banner';
        return view('shop.form', compact('form', 'sidebar', 'flag'));
    }

    /**
     * 添加展示图逻辑
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function storeBanner()
    {
        $this->authorize('shop_store_cover_add');
        $form = $this->form(BannerForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['type'] = Banner::TYPE_SHOP;
        $data['sort'] = $data['sort'] ?? 0;
        if ($data['aim'] == 'url' && empty($data['url'])) {
            return redirect()->back()->withErrors("地址字段不能为空")->withInput();
        }
        if ($data['aim'] != 'url' && empty($data['link_id'])) {
            return redirect()->back()->withErrors("商品不能为空")->withInput();
        }
        Banner::query()->create($data);
        return redirect()->route('admin.shop.banner');
    }

    /**
     * 删除展示图
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function delBanner($id)
    {
        $this->authorize('shop_store_cover_del');
        Banner::query()->where('id', $id)->delete();
        return redirect()->route('admin.shop.banner');
    }

    /**
     * 店铺会员列表
     * @param $id
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|\Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function getMember($id, Request $request)
    {
        $this->authorize('shop_store_member');
        $search = $request->input('search');
        $export = $request->input('export', 0);
        $shop = Shop::query()->find($id);
        $query = Member::query()
            ->join('users', 'users.id', '=', 'members.user_id')
            ->where('members.shop_id', $id)
            ->where('users.level', 1);
        if (!empty($search)) {
            $query->where('users.nickname', 'like', "%" . $search . "%");
        }
        if ($export) {
            $data = $query->get()
                ->map(function ($item) {
                    return [
                        $item->nickname,
                        $item->name,
                        $item->mobile,
                        $item->quota / 100,
                        $item->rebate / 100
                    ];
                });
            return (new MemberExport("{$shop->name}会员名单.xlsx", $data->all()))->downLoad();
        }
        $data = $query->paginate(20);
        $sidebar = 'shop';
        return view('shop.member', compact('data', 'sidebar', 'shop', 'search'));
    }

    /**
     * 添加会员-》页面
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function createMember($id)
    {
        $this->authorize('shop_store_member_add');
        $form = $this->form(MemberForm::class, [
            'method' => 'PUT',
            'url' => route('admin.shop.member.store', ['id' => $id]),
        ]);
        $sidebar = 'shop';
        return view('shop.form', compact('form', 'sidebar'));
    }

    /**
     * 添加会员逻辑
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function storeMember($id)
    {
        $this->authorize('shop_store_member_add');
        $form = $this->form(MemberForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $member = Member::query()
            ->where('shop_id', $id)
            ->where('user_id', $data['user_id'])
            ->first();
        if (!is_null($member)) {
            return redirect()->back()->with('warning', "用户已经是会员")->withInput();
        }
        $user = User::query()->find($data['user_id']);
        if ($user->level < 1) {
            $user->update([
                'level' => 1,
            ]);
        }
        Member::query()
            ->create([
                'shop_id' => $id,
                'user_id' => $data['user_id'],
                'quota' => $data['quota'] * 100,
                'rebate' => $data['rebate'] * 100,
            ]);
        return redirect()->route('admin.shop.member', ['id' => $id]);
    }

//    public function editBanner($id)
//    {
//        $shop = Shop::query()->find($id);
//        $form = $this->form( BannerForm::class, [
//            'method' => 'PUT',
//            'url' => route('admin.shop.banner.store'),
//            'model' => $shop,
//        ]);
//        $sidebar = 'banner';
//
//        return view('shop.form', compact('form', 'sidebar'));
//    }
//
//    public function updateBanner($id)
//    {
//        $shop = Shop::query()->find($id);
//        $form = $this->form( BannerForm::class, [
//            'method' => 'PUT',
//            'url' => route('admin.shop.banner.store'),
//            'model' => $shop,
//        ]);
//        $sidebar = 'banner';
//        return view('shop.form', compact('form', 'sidebar'));
//    }

    /**
     * 推荐商品列表
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function getRecommend($id)
    {
        $this->authorize('shop_store_recommend');
        $data = ShopRecommend::query()
            ->where('shop_id', $id)
            ->get();
        $shop = Shop::query()->find($id);
        if ($shop->type == Shop::TYPE_PHOTO) {
            $goods = GoodPackage::query()
                ->whereIn('id', $data->pluck('link_id')->all())
                ->get()
                ->keyBy('id');
        } else {
            $goods = Good::query()
                ->whereIn('id', $data->pluck('link_id')->all())
                ->get()
                ->keyBy('id');
        }
        $sidebar = 'shop';
        return view('shop.recommend', compact('data', 'goods', 'sidebar', 'shop'));
    }

    /**
     * 添加推荐-》页面
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function createRecommend($id)
    {
        $this->authorize('shop_store_recommend_add');
        $shop = Shop::query()->find($id);
        $form = $this->form(ShopRecommendForm::class, [
            'method' => 'PUT',
            'url' => route('admin.shop.recommend.store', ['id' => $id]),
        ]);
        $sidebar = 'shop';
        $flag = 'recommend';
        return view('shop.form', compact('form', 'sidebar', 'shop', 'flag'));
    }

    /**
     * 添加展示图逻辑
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function storeRecommend($id)
    {

        $this->authorize('shop_store_recommend_add');
        $form = $this->form(ShopRecommendForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        ShopRecommend::query()
            ->create([
                'shop_id' => $id,
                'link_id' => $data['link_id'],
            ]);
        return redirect()->route('admin.shop.recommend', ['id' => $id]);
    }


    /**
     * 删除展示图
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function deleteRecommend($id)
    {
        $this->authorize('shop_store_recommend_del');
        ShopRecommend::query()
            ->where('id', $id)
            ->delete();
        return redirect()->back();
    }
}
